package com.atguigu.gulimall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gulimall.order.pay.AlipayTemplate;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.PayAsyncVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author 小坏
 * @Date 2021/2/25 13:48
 * @Version 1.0
 * @program: 父工程 gulimall 万物起源之地
 */

@RestController
public class OrderPayedListener {

    @Autowired
    private OrderService orderService;


    @Autowired
    private AlipayTemplate alipayTemplate;

    /**
     * 支付宝异步通知
     * 1、验签成功修改订单的状态
     * 2、失败
     *
     * @return
     */
    @PostMapping("/payed/notify")
    public String handleAliPayed(PayAsyncVo payAsyncVo, HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //只要我们收到了支付宝给我们的异步通知，告诉我们的订单支付成功。返回success、支付宝就再也不通知
//        Map<String, String[]> map = request.getParameterMap ();
//        System.out.println ("支付宝通知到位了" + map);

        boolean b = notifyUrl (payAsyncVo, request);
        if (b) {
            System.out.println ("签名验证成功");
            String result = orderService.handlePayResult (payAsyncVo);
            return result;
        } else {
            System.out.println ("签名验证失败");
            return "error";
        }
    }


    private boolean notifyUrl(PayAsyncVo vo, HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String> ();
        Map requestParams = request.getParameterMap ();
        for (Iterator iter = requestParams.keySet ().iterator (); iter.hasNext (); ) {
            String name = (String) iter.next ();
            String[] values = (String[]) requestParams.get (name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
//            valueStr = new String (valueStr.getBytes ("ISO-8859-1"), "utf-8");
            params.put (name, valueStr);
        }


        boolean verify_result = AlipaySignature.rsaCheckV1 (params, alipayTemplate.getAlipay_public_key (), alipayTemplate.getCharset (), alipayTemplate.getSign_type ());
        return verify_result;
    }
}
